import { parseTime } from './common'
import store from '@/store'
import { getToken } from '@/utils/auth'
/**
 * 表格时间格式化
 */
export function formatDate(cellValue) {
  if (cellValue == null || cellValue == "") return "";
  var date = new Date(cellValue)
  var year = date.getFullYear()
  var month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  var day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
  var hours = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  var minutes = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  var seconds = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()
  return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
}
export function getNowDate() {
  let date = new Date()
  let year = date.getFullYear()
  let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
  let day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()

  return '' + year + "." + month + "." + day
}
/**
 * @param {numbber} money 金额转大写
 */
export function transformStr(money) {
  if(money && !isNaN(parseFloat(money)) && isFinite(money)) {
   // 默认值设置为“零元整”，如果输入为空或非法，则返回这个默认值
   let cnMoney = '零元整';
   // 用于构建输出字符串的变量
   let strOutput = '';
   // 中文单位数组，从高到低排列
   let strUnit = '仟佰拾亿仟佰拾万仟佰拾元角分';
   // 定义数字位数字符串
   let numCapitalLetters = '零壹贰叁肆伍陆柒捌玖';
   // 将传入的金额字符串后添加两个零，确保小数部分存在
   money += '00';
   // 查找小数点的位置
   let intPos = money.indexOf('.');
   if(intPos >= 0) {
    // 如果存在小数点，则移除小数点，并保留前两位作为小数部分
    money = money.substring(0, intPos) + money.substr(intPos + 1, 2);
   }
   // 长度限制
   if((strUnit.length - money.length) < 0) return '长度超出限制，最大支持千亿位';
   // 根据money的长度裁剪strUnit，以匹配money中每个数字对应的中文单位
   strUnit = strUnit.substr(strUnit.length - money.length);
   // 遍历money中的每一个字符
   for(var i = 0; i < money.length; i++) {
    // 对应数字转换为中文大写，并加上相应的中文单位
    strOutput += numCapitalLetters.substr(money.substr(i, 1), 1) + strUnit.substr(i, 1);
   }
   // 使用正则表达式处理中文大写金额字符串，进行格式化
   cnMoney = strOutput
   .replace(/零角零分$/, '整') // 如果最后是“零角零分”，替换为“整”
   .replace(/零[仟佰拾]/g, '零') // 移除多余的零（如“零仟”、“零佰”等）
   .replace(/零{2,}/g, '零') // 连续多个零只保留一个
   .replace(/零([亿|万])/g, '$1') // 去掉亿、万前面的零
   .replace(/零+元/, '元') // 去掉元前面的所有零
   .replace(/亿零{0,3}万/, '亿') // 如果亿后面有零和万，只保留亿
   .replace(/^元/, '零元'); // 如果最开始就是元，添加“零”
   
   // 返回最终处理后的中文大写金额字符串
   return cnMoney;
  }
  else {
   return '非法参数或参数不存在';
  }
}
/**
 * @param {date} time 需要转换的时间
 * @param {String} fmt 需要转换的格式 如 yyyy-MM-dd、yyyy-MM-dd HH:mm:ss
 */
export function formatTime1(time, fmt) {
  if (!time) return '';
  else {
    const date = new Date(time);
    const o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'H+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds(),
      'q+': Math.floor((date.getMonth() + 3) / 3),
      S: date.getMilliseconds(),
    };
    if (/(y+)/.test(fmt))
      fmt = fmt.replace(
        RegExp.$1,
        (date.getFullYear() + '').substr(4 - RegExp.$1.length)
      );
    for (const k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          RegExp.$1.length === 1
            ? o[k]
            : ('00' + o[k]).substr(('' + o[k]).length)
        );
      }
    }
    return fmt;
  }
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function getQueryObject(url) {
  url = url == null ? window.location.href : url
  const search = url.substring(url.lastIndexOf('?') + 1)
  const obj = {}
  const reg = /([^?&=]+)=([^?&=]*)/g
  search.replace(reg, (rs, $1, $2) => {
    const name = decodeURIComponent($1)
    let val = decodeURIComponent($2)
    val = String(val)
    obj[name] = val
    return rs
  })
  return obj
}

/**
 * @param {string} input value
 * @returns {number} output value
 */
export function byteLength(str) {
  // returns the byte length of an utf8 string
  let s = str.length
  for (var i = str.length - 1; i >= 0; i--) {
    const code = str.charCodeAt(i)
    if (code > 0x7f && code <= 0x7ff) s++
    else if (code > 0x7ff && code <= 0xffff) s += 2
    if (code >= 0xDC00 && code <= 0xDFFF) i--
  }
  return s
}

/**
 * @param {Array} actual
 * @returns {Array}
 */
export function cleanArray(actual) {
  const newArray = []
  for (let i = 0; i < actual.length; i++) {
    if (actual[i]) {
      newArray.push(actual[i])
    }
  }
  return newArray
}

/**
 * @param {Object} json
 * @returns {Array}
 */
export function param(json) {
  if (!json) return ''
  return cleanArray(
    Object.keys(json).map(key => {
      if (json[key] === undefined) return ''
      return encodeURIComponent(key) + '=' + encodeURIComponent(json[key])
    })
  ).join('&')
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

/**
 * @param {string} val
 * @returns {string}
 */
export function html2Text(val) {
  const div = document.createElement('div')
  div.innerHTML = val
  return div.textContent || div.innerText
}

/**
 * Merges two objects, giving the last one precedence
 * @param {Object} target
 * @param {(Object|Array)} source
 * @returns {Object}
 */
export function objectMerge(target, source) {
  if (typeof target !== 'object') {
    target = {}
  }
  if (Array.isArray(source)) {
    return source.slice()
  }
  Object.keys(source).forEach(property => {
    const sourceProperty = source[property]
    if (typeof sourceProperty === 'object') {
      target[property] = objectMerge(target[property], sourceProperty)
    } else {
      target[property] = sourceProperty
    }
  })
  return target
}

/**
 * @param {HTMLElement} element
 * @param {string} className
 */
export function toggleClass(element, className) {
  if (!element || !className) {
    return
  }
  let classString = element.className
  const nameIndex = classString.indexOf(className)
  if (nameIndex === -1) {
    classString += '' + className
  } else {
    classString =
      classString.substr(0, nameIndex) +
      classString.substr(nameIndex + className.length)
  }
  element.className = classString
}

/**
 * @param {string} type
 * @returns {Date}
 */
export function getTime(type) {
  if (type === 'start') {
    return new Date().getTime() - 3600 * 1000 * 24 * 90
  } else {
    return new Date(new Date().toDateString())
  }
}

/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在，重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

/**
 * This is just a simple version of deep copy
 * Has a lot of edge cases bug
 * If you want to use a perfect deep copy, use lodash's _.cloneDeep
 * @param {Object} source
 * @returns {Object}
 */
export function deepClone(source) {
  if (!source && typeof source !== 'object') {
    throw new Error('error arguments', 'deepClone')
  }
  const targetObj = source.constructor === Array ? [] : {}
  Object.keys(source).forEach(keys => {
    if (source[keys] && typeof source[keys] === 'object') {
      targetObj[keys] = deepClone(source[keys])
    } else {
      targetObj[keys] = source[keys]
    }
  })
  return targetObj
}

/**
 * @param {Array} arr
 * @returns {Array}
 */
export function uniqueArr(arr) {
  return Array.from(new Set(arr))
}

/**
 * @returns {string}
 */
export function createUniqueString() {
  const timestamp = +new Date() + ''
  const randomNum = parseInt((1 + Math.random()) * 65536) + ''
  return (+(randomNum + timestamp)).toString(32)
}

/**
 * Check if an element has a class
 * @param {HTMLElement} elm
 * @param {string} cls
 * @returns {boolean}
 */
export function hasClass(ele, cls) {
  return !!ele.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'))
}

/**
 * Add class to element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function addClass(ele, cls) {
  if (!hasClass(ele, cls)) ele.className += ' ' + cls
}

/**
 * Remove class from element
 * @param {HTMLElement} elm
 * @param {string} cls
 */
export function removeClass(ele, cls) {
  if (hasClass(ele, cls)) {
    const reg = new RegExp('(\\s|^)' + cls + '(\\s|$)')
    ele.className = ele.className.replace(reg, ' ')
  }
}

export function makeMap(str, expectsLowerCase) {
  const map = Object.create(null)
  const list = str.split(',')
  for (let i = 0; i < list.length; i++) {
    map[list[i]] = true
  }
  return expectsLowerCase
    ? val => map[val.toLowerCase()]
    : val => map[val]
}

export const exportDefault = 'export default '

export const beautifierConf = {
  html: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'separate',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: false,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true
  },
  js: {
    indent_size: '2',
    indent_char: ' ',
    max_preserve_newlines: '-1',
    preserve_newlines: false,
    keep_array_indentation: false,
    break_chained_methods: false,
    indent_scripts: 'normal',
    brace_style: 'end-expand',
    space_before_conditional: true,
    unescape_strings: false,
    jslint_happy: true,
    end_with_newline: true,
    wrap_line_length: '110',
    indent_inner_html: true,
    comma_first: false,
    e4x: true,
    indent_empty_lines: true
  }
}

// 首字母大小
export function titleCase(str) {
  return str.replace(/( |^)[a-z]/g, L => L.toUpperCase())
}

// 下划转驼峰
export function camelCase(str) {
  return str.replace(/_[a-z]/g, str1 => str1.substr(-1).toUpperCase())
}

export function isNumberStr(str) {
  return /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g.test(str)
}
//审核状态
export function formatterState(state,pageName) {
  switch (state) {
    case 0:
      return {
        text: '暂存',
        type: 'info',
        color: '',
        icon: 'el-icon-star-on'
      }
    case 1:
      return {
        text: '审核中',
        type: '',
        color: '',
        icon: 'el-icon-more'
      }
    case 2:
      return {
        text: pageName=='contract'?'已通过':'已立项',
        color: '',
        icon: 'el-icon-success',
        type: 'success'
      }
    case 3:
      return {
        text:'驳回',
        color: '',
        icon: 'el-icon-error',
        type: 'danger'
      }
    case 9:
      return {
        text:'已撤销',
        color: '',
        icon: 'el-icon-more',
        type: 'warning'
      }
    default:
      return {
        text: '--',
        color: '',
        icon: 'el-icon-bell',
        type: 'info'
      }
  }
}
//审核进度状态
export function auditProcessStatus(state) {
  var status = 0
  if(state){
    status = Number(state)
  }else{
    status = state
  }
  switch (status) {
    case 0:
      return {
        text: '待审核',
        color: '#409EFF',
        type: '',
        icon: 'el-icon-more'
      }

    case 1:
      return {
        text: '通过',
        color: '#67C23A',
        type: 'success',
        icon: 'el-icon-success'
      }

    case 2:
      return {
        text: '驳回',
        color: '#F56C6C',
        type: 'danger',
        icon: 'el-icon-error'
      }
    case -1:
      return {
        text: '申请',
        color: '#409EFF',
        type: 'info',
        icon: 'el-icon-user-solid'
      }
    case 9:
      return {
        text: '撤销',
        color: '#E6A23C',
        type: 'danger',
        icon: 'el-icon-user-solid'
      }
    default:
      return {
        text: '--',
        color: '',
        icon: 'el-icon-bell'
      }
  }
}
//局部使用 合同收款项计算
export function conrractCount(a, b) {
  // 将 a 和 b 转换为数字进行计算，如果转换失败则返回 "--"
  const numA = parseFloat(a);
  const numB = parseFloat(b);
  
  // 计算 a 减 b
  const result = isNaN(numA) || isNaN(numB) ? '--' : numA - numB;
  
  return result;
}
//转换类型 未 number
export function convertToNumberEnhanced(value) {
  switch (typeof value) {
    case 'number':
      return value;
      
    case 'string':
      // 去除首尾空格
      const trimmed = value.trim();
      
      // 处理空字符串
      if (trimmed === '') return 0;
      
      // 处理布尔值字符串
      if (trimmed.toLowerCase() === 'true') return 1;
      if (trimmed.toLowerCase() === 'false') return 0;
      
      // 尝试转换为数字
      const num = parseFloat(trimmed);
      return isNaN(num) ? 0 : num;
      
    case 'boolean':
      return value ? 1 : 0;
      
    default:
      // 处理 null、undefined、对象、数组等
      return 0;
  }
}
// 获取字典值
export function getAllDict() {
  if (!getToken()) return
  store.dispatch('getProductType')
  store.dispatch('getYesno')
  store.dispatch('getProceedsReturn')
  store.dispatch('getPhysicalReturn')
  store.dispatch("getRewardIntegral")
  store.dispatch("getRewardSuperiorIntegral")
  store.dispatch("getRewardAmount")
  store.dispatch("getRewardSuperiorAmount")
  store.dispatch("getBreedCycle")
  store.dispatch("getCowVariety")
  store.dispatch("getProductState")
  store.dispatch("getProductTag")
  store.dispatch("getCowSex")
  store.dispatch("getHealthState")
  store.dispatch("getVaccineState")
  store.dispatch("getInsuranceState")
  store.dispatch("getInsuranceCompany")
  store.dispatch("getCowState")
  store.dispatch("getCowSellState")
  store.dispatch("getOrderType")
  store.dispatch("getOrderState")
  store.dispatch("getEarTagState")
  store.dispatch("getCouponType")
  store.dispatch("getCouponUsageScenario")
  store.dispatch("getCouponProvideType")
  store.dispatch("getCouponState")
  store.dispatch("getMonitorBrand")
  store.dispatch("getMonitorState")
  store.dispatch("getExpressCompany")
  store.dispatch('getPhysicalEarningState')
  store.dispatch('getMemCouponState')
  store.dispatch("getFosterCowState")
  store.dispatch('getMemRealNameState')
  store.dispatch("getCowPortionState")
  store.dispatch("getWithdrawalApplyType")
  store.dispatch('getWithdrawalApplyAuditState')
  store.dispatch('getWithdrawalApplyTransferState')
  store.dispatch('getBalanceType')
  store.dispatch('getBalanceDealState')
  store.dispatch("getWithdrawState")
  store.dispatch('getIncomeType')
  store.dispatch('getWithdrawType')
  store.dispatch('getProceedsReturnState')
  store.dispatch("getIntegralChangeType")
  store.dispatch('getChannelType')
  store.dispatch('getChannelState')
}

